package com.jxc.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.RoleResourceDaoI;
import com.jxc.model.po.Resource;
import com.jxc.model.po.Role;
import com.jxc.model.po.RoleResource;
import com.jxc.model.vo.VRole;

@Service("roleResourceDao")
public class RoleResourceDaoImpl implements RoleResourceDaoI {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<VRole> getRoleByResource(Long resourceId) {
		String hql = "from RoleResource t where t.resource.id=" + resourceId;
		Session session = sessionFactory.openSession();
		List<RoleResource> list = session.createQuery(hql)
				.list();
		List<Role> roles = new ArrayList<Role>();
		if (list != null && list.size() > 0) {
			for (RoleResource rr : list) {
				roles.add(rr.getRole());
			}
		}
		List<VRole> result = changeModel(roles);
		session.close();
		return result;
	}

	private List<VRole> changeModel(List<Role> roles) {
		List<VRole> vRoles = new ArrayList<VRole>();
		if (roles != null && roles.size() > 0) {
			for (Role role : roles) {
				VRole vRole = new VRole();
				BeanUtils.copyProperties(role, vRole);

				List<RoleResource> resources = role.getRoleResources();
				String resourceIds = "";
				String resourceNames = "";
				boolean b = false;
				if (resources != null && resources.size() > 0) {
					for (RoleResource roleResource : resources) {
						Resource resource = roleResource.getResource();
						if (resource != null) {
							if (b) {
								resourceIds += ",";
								resourceNames += ",";
							}
							resourceIds += resource.getId();
							resourceNames += resource.getName();
							b = true;
						}
					}
				}
				vRole.setResourceIds(resourceIds);
				vRole.setResourceNames(resourceNames);
				vRoles.add(vRole);
			}
		}
		return vRoles;
	}

}
